package com.payment.controller.paynotify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.payment.entity.common.UserNoCardOrder;
import com.payment.entity.common.UserOrderPackage;
import com.payment.entity.common.UserOrderPayment;
import com.payment.entity.newrequestnotify.request.RequestNotify;
import com.payment.entity.newrequestnotify.response.ResponseNotify;
import com.payment.entity.payresults.OceanPaymentResults;
import com.payment.entity.payresults.oceanpay.response.OceanPaymentNotifyResponse;
import com.payment.service.*;
import com.payment.utils.Constant;
import com.payment.utils.HMACSHA256;
import com.payment.utils.HttpUtil;
import com.payment.utils.JaxbUtil;
import com.payment.utils.payment.OceanPayConstants;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Api(description = "钱海信用卡支付回调")
/**
 * 1，使用领科的钱海信用卡收款账号收款，钱海信用卡支付回调接口：
 *
 * 2，适用于新的客户：最新版的的领科 H5 和其他想要使用领科收款接口收款的（可以是客户自己的账号或者领科发账号）客户；
 *
 * 3，更新的数据表为：user_order_package_t，user_order_payment_t；
 *
 *  4，更新的数据库为：v-shop
 *
 *  5，很重要：现在已经废弃不再使用此种支付方式，接口废弃
 *
 * @author lm
 * @date 2019/11/06
 */
public class OceanPaymentNotifyController {

    private static Logger logger = Logger.getLogger(OceanPaymentNotifyController.class);
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");

    @Autowired
    private NotificationpaymentService notificationpaymentService;
    @Autowired
    private PartnerService partnerService;
    @Autowired
    private UserOrderPackageService orderService;
    @Autowired
    private UserOrderPaymentService paymentService;
    @Autowired
    private UserNoCardOrderService userNoCardOrderService;

    /***
     * 钱海支付结果回调
     * @param reStr
     * @return
     */
    @PostMapping(value = "notifyOceanPay")
    @CrossOrigin
    private String noticeUrl(@RequestBody String reStr) {

        logger.info("钱海支付开始回调：" + reStr);
        if (StringUtils.isNotBlank(reStr)) {
            String jsonString;
            OceanPaymentNotifyResponse response = new JaxbUtil(OceanPaymentNotifyResponse.class).fromXml(reStr, "utf-8");

            if (response != null) {

                String signValue = response.getSignValue();
                String response_type = response.getResponse_type();
                String account = response.getAccount();
                String terminal = response.getTerminal();
                String methods = response.getMethods();
                String order_number = response.getOrder_number();
                String payId = response.getOrder_number();
                String order_currency = response.getOrder_currency();
                String order_amount = response.getOrder_amount();
                String order_notes = response.getOrder_notes();
                String card_number = response.getCard_number();
                String payment_country = response.getPayment_country();
                String payment_id = response.getPayment_id();
                String payment_authType = response.getPayment_authType();
                String payment_status = response.getPayment_status();
                String payment_details = response.getPayment_details();
                String payment_risk = response.getPayment_risk();
                String payment_solutions = response.getPayment_solutions();
                String auth_reason = response.getAuth_reason();
                String order_operator = response.getOrder_operator();

                StringBuffer buffer = new StringBuffer();
                buffer.append(account);
                buffer.append(terminal);
                buffer.append(order_number);
                buffer.append(order_currency);
                buffer.append(order_amount);
                buffer.append(order_notes);
                buffer.append(card_number);
                buffer.append(payment_id);
                buffer.append(payment_authType);
                buffer.append(payment_status);
                buffer.append(payment_details);
                buffer.append(payment_risk);
                buffer.append(OceanPayConstants.secureCode);

                String sign = HMACSHA256.getSHA256StrJava(buffer.toString());
                logger.info("计算的sign值：" + sign + ";报文发过来的signValue：" + signValue);

                if (StringUtils.isNotBlank(order_number) && StringUtils.isNotBlank(payId) && StringUtils.isNotBlank(payment_status)) {

                    int count = notificationpaymentService.findCountByOceanOrderNumber(order_number);
                    if (count <= 0) {
                        OceanPaymentResults oceanPaymentResults = new OceanPaymentResults();
                        oceanPaymentResults.setSignValue(signValue);
                        oceanPaymentResults.setResponse_type(response_type);
                        oceanPaymentResults.setAccount(account);
                        oceanPaymentResults.setTerminal(terminal);
                        oceanPaymentResults.setMethods(methods);
                        oceanPaymentResults.setOrder_number(order_number);
                        oceanPaymentResults.setOrder_currency(order_currency);
                        oceanPaymentResults.setOrder_amount(order_amount);
                        oceanPaymentResults.setOrder_notes(order_notes);
                        oceanPaymentResults.setCard_number(card_number);
                        oceanPaymentResults.setPayment_country(payment_country);
                        oceanPaymentResults.setPayment_id(payment_id);
                        oceanPaymentResults.setPayment_authType(payment_authType);
                        oceanPaymentResults.setPayment_status(payment_status);
                        oceanPaymentResults.setPayment_details(payment_details);
                        oceanPaymentResults.setPayment_risk(payment_risk);
                        oceanPaymentResults.setPayment_solutions(payment_solutions);
                        oceanPaymentResults.setAuth_reason(auth_reason);
                        oceanPaymentResults.setOrder_operator(order_operator);
                        notificationpaymentService.insertOceanPaymentResults(oceanPaymentResults);
                    }
                    //支付成功
                    if (payment_status.equals("1")) {

                        int c = orderService.findPayIdByNotify(payId);
                        if (c <= 0) {
                            // 成功的回调数据入库：根据支付id和金额入库：user_order_package_t
                            List<UserOrderPackage> deviceCodeList = orderService.queryDeviceCodeByPayId(payId);

                            for (UserOrderPackage uo : deviceCodeList) {
                                String deviceCode = uo.getDeviceCode();

                                if (StringUtils.isNotBlank(deviceCode)) {
                                    String str1 = deviceCode.substring(0, 1);
                                    if (!str1.equals("卡") && !str1.equalsIgnoreCase("c")) {
                                        UserOrderPackage order = new UserOrderPackage();
                                        //直接已完成
                                        order.setOrderStatus("3");
                                        order.setPayId(payId);
                                        order.setPayCurrency(order_currency);
                                        order.setPayAmount(order_amount);
                                        order.setPayType(Constant.PAY_OCEANPAY);
                                        order.setPayRst("success");
                                        order.setIsNotify("1");
                                        order.setPayAccount("1");
                                        order.setTransactionId(payment_id);
                                        order.setUpdateDate(sdf.format(new Date()));
                                        order.setOrderTime(s.format(new Date()));
                                        orderService.updateWeiXinPayRst(order);

                                    } else {
                                        UserOrderPackage order = new UserOrderPackage();
                                        //待发货
                                        order.setOrderStatus("1");
                                        order.setPayId(payId);
                                        order.setPayCurrency(order_currency);
                                        order.setPayAmount(order_amount);
                                        order.setPayType(Constant.PAY_OCEANPAY);
                                        order.setPayRst("success");
                                        order.setIsNotify("1");
                                        order.setPayAccount("1");
                                        order.setTransactionId(payment_id);
                                        orderService.updateWeiXinPayRst(order);
                                    }
                                } else {
                                    //deviceCode没取到值，但是支付记录还是要入库
                                    UserOrderPackage order = new UserOrderPackage();
                                    order.setUpdateDate(sdf.format(new Date()));
                                    order.setOrderTime(s.format(new Date()));
                                    //直接已完成
                                    order.setOrderStatus("3");
                                    order.setPayId(payId);
                                    order.setPayCurrency(order_currency);
                                    order.setPayAmount(order_amount);
                                    order.setPayType(Constant.PAY_OCEANPAY);
                                    order.setPayRst("success");
                                    order.setIsNotify("1");
                                    order.setPayAccount("1");
                                    order.setTransactionId(payment_id);
                                    orderService.updateWeiXinPayRst(order);
                                }

                            }

                            //成功的回调数据入库：根据支付id和金额入库：user_order_payment_t
                            UserOrderPayment payment = new UserOrderPayment();
                            payment.setPayId(payId);
                            payment.setPayCurrency(order_currency);
                            payment.setPayAmount(order_amount);
                            payment.setPayType(Constant.PAY_OCEANPAY);
                            payment.setPayRst("success");
                            payment.setTransactionId(payment_id);
                            paymentService.updateWeiXinPayRst(payment);

                            //无卡订单支付结果入库：user_nocard_order_t
                            UserNoCardOrder noCardOrder = new UserNoCardOrder();
                            noCardOrder.setPayId(payId);
                            noCardOrder.setPayRst("success");
                            userNoCardOrderService.updatePayRst(noCardOrder);

                            //将去北京做支付结果通知的工作交到具体的orderService处理类中去
                            List<UserOrderPackage> userOrderList = orderService.queryOrderByPayIdAndAmount(payId, order_amount);

                            if (userOrderList != null && !userOrderList.isEmpty()) {
                                for (UserOrderPackage u : userOrderList) {
                                    String partnerCode = u.getPartnerCode();
                                    String orderId = u.getOrderId();
                                    String deviceId = u.getDeviceCode();
                                    String Amount = u.getPayAmount();
                                    String secret = partnerService.findSecretByPartnerCode(partnerCode);
                                    logger.info("查询到的订单orderId是:" + orderId + ";DeviceId是:" + deviceId + ";payAmount是：" + Amount + ";密钥是：" + secret);

                                    RequestNotify notify = new RequestNotify();
                                    notify.setDeviceId(deviceId);
                                    notify.setOrderId(orderId);
                                    notify.setPayAmount(Amount);
                                    notify.setPayType(Constant.PAY_OCEANPAY);
                                    notify.setSecret(secret);
                                    notify.setPartnerCode(partnerCode);
                                    // 开始组装json
                                    String requestStr = JSON.toJSONString(notify);
                                    logger.info("请求北京的接口请求报文：" + requestStr);
                                    String url = Constant.requestURI + Constant.iot_notify;
                                    // 发送post请求，并接收返回结果
                                    String returnStr = HttpUtil.httpPost(url, requestStr);
                                    logger.info("北京回复的下发接口响应报文：" + returnStr);
                                    ResponseNotify re = JSONArray.parseObject(returnStr, ResponseNotify.class);

                                    if (re != null) {
                                        if (true == Constant.RET_CODE_0000.equalsIgnoreCase(re.getRetCode()) || true == Constant.RET_CODE_0113.equalsIgnoreCase(re.getRetCode())) {
                                            UserOrderPackage user = new UserOrderPackage();
                                            user.setOrderId(orderId);
                                            user.setPayId(payId);
                                            user.setIsNotify("0");
                                            orderService.updateWeiXinIsNotify(user);
                                            logger.info("同步成功");

                                        } else {
                                            logger.info("同步不成功");
                                            return null;
                                        }
                                    } else {
                                        logger.info("同步接口异常");
                                        return null;
                                    }


                                }

                            } else {
                                logger.info("数据库查询到的订单为null");
                                return null;
                            }


                        }

                    } else {//支付失败 payment_status =0
                        logger.info("钱海回调的支付结果是支付失败：" + payment_status);
                        int c = orderService.findPayIdByNotify(payId);
                        if (c <= 0) {
                            // 成功的回调数据入库：根据支付id和金额入库：user_order_package_t
                            List<UserOrderPackage> deviceCodeList = orderService.queryDeviceCodeByPayId(payId);

                            for (UserOrderPackage uo : deviceCodeList) {
                                String deviceCode = uo.getDeviceCode();

                                if (StringUtils.isNotBlank(deviceCode)) {
                                    String str1 = deviceCode.substring(0, 1);
                                    if (!str1.equals("卡") && !str1.equalsIgnoreCase("c")) {
                                        UserOrderPackage order = new UserOrderPackage();
                                        //直接已完成
                                        order.setPayId(payId);
                                        order.setPayCurrency(order_currency);
                                        order.setPayAmount(order_amount);
                                        order.setPayType(Constant.PAY_OCEANPAY);
                                        order.setPayRst("fail");
                                        order.setIsNotify("1");
                                        order.setPayAccount("1");
                                        order.setUpdateDate(sdf.format(new Date()));
                                        order.setOrderTime(s.format(new Date()));
                                        order.setTransactionId(payment_id);
                                        orderService.updateWeiXinPayRst(order);

                                    } else {
                                        UserOrderPackage order = new UserOrderPackage();
                                        //待发货
                                        order.setTransactionId(payment_id);
                                        order.setPayId(payId);
                                        order.setPayCurrency(order_currency);
                                        order.setPayAmount(order_amount);
                                        order.setPayType(Constant.PAY_OCEANPAY);
                                        order.setPayRst("fail");
                                        order.setIsNotify("1");
                                        order.setPayAccount("1");

                                        orderService.updateWeiXinPayRst(order);
                                    }
                                } else {
                                    //deviceCode没取到值，但是支付记录还是要入库
                                    UserOrderPackage order = new UserOrderPackage();
                                    order.setPayId(payId);
                                    order.setPayCurrency(order_currency);
                                    order.setPayAmount(order_amount);
                                    order.setPayType(Constant.PAY_OCEANPAY);
                                    order.setPayRst("fail");
                                    order.setIsNotify("1");
                                    order.setPayAccount("1");
                                    order.setTransactionId(payment_id);
                                    orderService.updateWeiXinPayRst(order);
                                }

                            }

                            //成功的回调数据入库：根据支付id和金额入库：user_order_payment_t
                            UserOrderPayment payment = new UserOrderPayment();
                            payment.setPayId(payId);
                            payment.setPayCurrency(order_currency);
                            payment.setPayAmount(order_amount);
                            payment.setPayType(Constant.PAY_OCEANPAY);
                            payment.setPayRst("success");
                            payment.setTransactionId(payment_id);
                            paymentService.updateWeiXinPayRst(payment);

                            //无卡订单支付结果入库：user_nocard_order_t
                            UserNoCardOrder noCardOrder = new UserNoCardOrder();
                            noCardOrder.setPayId(payId);
                            noCardOrder.setPayRst("success");
                            userNoCardOrderService.updatePayRst(noCardOrder);
                        }
                    }

                    //给钱海回复信息
                    return "receive-ok";

                } else {
                    logger.info("钱海回调的支付参数为null");
                    return null;
                }

            } else {
                logger.info("钱海回调报文为null");
                return null;
            }

        } else {
            logger.info("钱海回调内容为空");
            return null;
        }
    }
}